<?php

use App\Blog;
use App\Member;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        // 1.创建模型
        // php artisan make:model Admin
        // php artisan make:model Cate
        // php artisan make:model Tag

        // 2.去migrate中设计表，并执行

        // 3.获取表的字段
        // $this->getTableCols([
        //     'cates', 'tags'
        // ]);die;

        // 4.将字段复制到BlogFactory去添加表内容

        // 清空表内容
        $this->clearTableContent([
            'members',
        ]);
        // 5.创建表数据
        // factory(Blog::class, 100)->create();
        factory(Member::class, 100)->create();
        
        // 6.添加单一数据
        // $this->insert();

        // 7.执行填充
        // alias pad="php artisan db:seed"
        // php artisan db:seed
        echo "done\r\n";
    }

    /**
     * 获取表字段
     */
    private function getTableCols(array $tables)
    {
        if (empty($tables)) {
            return ;
        }

        foreach($tables as $table) {
            echo "{$table}:\r\n";
            $result = DB::select("select COLUMN_NAME from information_schema.COLUMNS where table_name = '{$table}';");
            $cols = array_column($result, 'COLUMN_NAME');
            foreach($cols as $val) {
                if(in_array($val, ['id', 'created_at', 'updated_at'])) {
                    continue;
                }
                echo "'{$val}' => '', \n\r";
            }
            echo "\r\n";
        }
    }

    /**
     * 清空表内容
     */
    private function clearTableContent(array $tables)
    {
        if (empty($tables)) {
            return ;
        }
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');//禁用外键约束
        foreach($tables as $table) {
            DB::table($table)->truncate();
        }
        DB::statement('SET FOREIGN_KEY_CHECKS = 1');//启用外键约束
    }

    private function insert($table, $data)
    {
        $now = time();
        $now2= date('Y-m-d H:i:s', $now);
        $data['created_at'] = $now2;
        $data['updated_at'] = $now2;
        DB::table($table)->insert($data);
    }
}
